import { createApp } from 'vue';
import App from '@/App.vue';

const app = createApp(App);

app.directive('drag', {
    mounted: function (el) {
        let dragDom = el; // 当前元素
        dragDom.style.position = 'absolute';
        dragDom.style.cursor = 'default';

        let isOnTopBorder = false;
        let disX = 0;
        let disY = 0;
        const borderWidth = 10;

        // 判断鼠标位置改变鼠标样式
        const checkMousePosition = function (e) {
            const rect = dragDom.getBoundingClientRect();
            isOnTopBorder = e.clientY >= rect.top && e.clientY <= rect.top + borderWidth;
            dragDom.style.cursor = isOnTopBorder ? 'move' : 'default';
        };

        dragDom.addEventListener('mousemove', checkMousePosition);

        dragDom.onmousedown = function (e) {
            const rect = dragDom.getBoundingClientRect();
            // 判断鼠标是否在边框范围内
            isOnTopBorder = e.clientY >= rect.top && e.clientY <= rect.top + borderWidth;
            if (isOnTopBorder) {
                // 计算鼠标相对元素的位置
                disX = e.clientX - dragDom.offsetLeft;
                disY = e.clientY - dragDom.offsetTop;

                // 绑定事件
                document.onmousemove = function (e) {
                    let left = e.clientX - disX;
                    let top = e.clientY - disY;
                    dragDom.style.left = `${left}px`;
                    dragDom.style.top = `${top}px`;
                };

                document.onmouseup = function () {
                    document.onmousemove = null;
                    document.onmouseup = null;
                };
            }
        };
    }
});

export default app;
